// 路由配置
import {createRouter, createWebHistory} from "vue-router";
import userUserStore from "@/store/index.js";
import {storeToRefs} from "pinia";
import axios from "axios";
// 路由配置规则
const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    //主页路由
    {
        path: "/home",
        name: "home",
        meta: {title: "后台管理系统"},
        component: () => import("@/pages/home.vue"),
        children: [
            {path: "/home", redirect:'/home/jobs' },
            {
                path: "jobs",
                name: "jobs",
                meta: {title: "岗位管理"},
                component: () => import("@/pages/jobs.vue"),
            },
            {
                path: "notice",
                name: "notice",
                meta: {title: "公告管理"},
                component: () => import("@/pages/notice.vue"),
            },
            {
                path: "noticeDetail/:id?",
                name: "noticeDetail",
                meta: {title: "公告详情"},
                component: () => import("@/pages/noticeDetail.vue"),
            },
            {
                path: "users",
                name: "users",
                meta: {title: "用户管理"},
                component: () => import("@/pages/users.vue"),
            },
            {
                path: "dataBoard",
                name: "dataBoard",
                meta: {title: "数据看板"},
                component: () => import("@/pages/dataBoard.vue"),
            },
            {
                path: "jobDetail/:id?",
                name: "jobDetail",
                meta: {title: "岗位详情"},
                component: () => import("@/pages/jobDetail.vue"),
            }
        ]
    },
    // 登录页面
    {
        path: "/login",
        name: "login",
        meta: {title: "登录"},
        component: () => import("@/pages/login.vue"),
    },
    //404页面
    {
        path: "/404",
        name: "404",
        meta: {title: "未找到该页面"},
        component: () => import("@/pages/404.vue"),
    },
    // 重定向
    {
        path: '/:pathMatch(.*)*',
        redirect: '/404'
    }
];


// 全局路由守卫进行登入鉴权
const router = createRouter({
    history: createWebHistory(), //使用模式
    routes: routes, // 导入路由配置规则
    linkActiveClass: "active", // 设置激活的样式类名
});
router.beforeEach((to, from, next) => {
    //先得到用户和token
    const store = userUserStore();
    const {username, token} = storeToRefs(store);

    //添加页面标题的
    if (to.meta.title) {
        document.title = to.meta.title; //修改网页的标题
    }
    if (to.path == '/login') {
        return next()
    }
    if (token.value) {
        axios.defaults.headers['Authorization'] = `Bearer ${token.value}`;
        return next()
    } else {
        return next('/login')
    }
});
export default router; //导出
